package com.lemon.smartsafety.ui.activity.safe.data.contract;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.DataInfo;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.event.contract.KeepRefreshEvent;
import com.lemon.smartsafety.entity.event.contract.KeepUnitEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.entity.safe.contract.AgencyInfoVo;
import com.lemon.smartsafety.entity.safe.contract.KeepContractVo;
import com.lemon.smartsafety.entity.safe.contract.YearVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.KeepContactServices;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.safe.constract.KeepYearListAdapter;
import com.lemon.smartsafety.ui.fragment.safe.contract.KeepContractUnitListFragment;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.TimeUtil;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.SwipeBackLayout;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/3/25.
 */
public class KeepContractPropActivity extends SwipeBackActivity {


    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.metContractYear)
    MaterialEditText metContractYear;
    @Bind(R.id.lineContractYear)
    LinearLayout lineContractYear;
    @Bind(R.id.select_unit_tip)
    TextView tvUnitTip;
    @Bind(R.id.metContractUnit)
    MaterialEditText metContractUnit;
    @Bind(R.id.imageArrow)
    ImageView imageArrow;
    @Bind(R.id.lineContractUnit)
    LinearLayout lineContractUnit;
    @Bind(R.id.metContractStart)
    MaterialEditText metContractStart;
    @Bind(R.id.lineContractStart)
    LinearLayout lineContractStart;
    @Bind(R.id.metContractEnd)
    MaterialEditText metContractEnd;
    @Bind(R.id.lineContractEnd)
    LinearLayout lineContractEnd;
    @Bind(R.id.radioYes)
    AppCompatRadioButton radioYes;
    @Bind(R.id.radioNo)
    AppCompatRadioButton radioNo;
    @Bind(R.id.btn_submit)
    Button trButton;
    @Bind(R.id.mainContainer)
    LinearLayout mainContainer;
    @Bind(R.id.swipeBackLayout)
    SwipeBackLayout swipeBackLayout;
    private CompanyInfo mCompanyInfo;
    private boolean isEdit = false;

    private String sTypeId = "1";
    /**
     * 编辑用的
     */
    private KeepContractVo mKeepContractVo;

    private AgencyInfoVo mAgencyInfoVo;


    private MaterialDialog.Builder mMaterialDialog;

    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.keep_contract_prop_title);
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mKeepContractVo = (KeepContractVo) getIntent().getSerializableExtra(BundleKey.KEEP_CONTRACT_VO);
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
            sTypeId = getIntent().getStringExtra(BundleKey.TYPE_ID);
        }


        if (null != mKeepContractVo) {
            isEdit = true;
        }

    }


    @Override
    protected void initViews() {
        super.initViews();
        metContractYear.setTag("");
        if (StringUtils.nullValue(sTypeId, "1").equals("2")) {
            this.setBarTitle(R.string.wuye_unit_prop_title);
            tvUnitTip.setText(R.string.wuye_unit_prop_contract_unit);
        }
        if (null == mCompanyInfo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
        }

        String currentYear = DateUtils.getCurrentYear() + "";
        metContractYear.setText(DataInfo.getStatusString(currentYear + "年", DataInfo.ColorStatus.STATUS_BLUE));
        metContractYear.setTag(currentYear);

        metContractStart.setText(DateUtils.getCurrentYMDDate());
        metContractEnd.setText(DateUtils.getCurrentDateByOffset(DateUtils.dateFormatYMD, Calendar.YEAR, 1));

        if (isEdit && !StringUtils.getBoolean(mKeepContractVo.getStatus())) {
            radioNo.setEnabled(false);
            radioYes.setEnabled(false);
            trButton.setVisibility(View.GONE);
            imageArrow.setVisibility(View.INVISIBLE);
        } else {
            trButton.setVisibility(View.VISIBLE);
            radioNo.setEnabled(true);
            radioYes.setEnabled(true);
          /*  lineContractYear.setBackgroundResource(R.drawable.base_click_pressed);
            lineContractUnit.setBackgroundResource(R.drawable.base_click_pressed);
            lineContractStart.setBackgroundResource(R.drawable.base_click_pressed);
            lineContractEnd.setBackgroundResource(R.drawable.base_click_pressed);*/

            metContractYear.setBackgroundResource(R.drawable.base_click_pressed);
            metContractUnit.setBackgroundResource(R.drawable.base_click_pressed);
            metContractStart.setBackgroundResource(R.drawable.base_click_pressed);
            metContractEnd.setBackgroundResource(R.drawable.base_click_pressed);
            imageArrow.setVisibility(View.VISIBLE);
        }


        if (isEdit) {
            initEditView(mKeepContractVo);
        }


    }


    /**
     * 初始化这个编辑视图的值
     *
     * @param vo
     */
    private void initEditView(KeepContractVo vo) {
        metContractYear.setText(DataInfo.getStatusString(vo.getKeep_year() + "年", DataInfo.ColorStatus.STATUS_BLUE));
        mAgencyInfoVo = vo.getAgencyInfoVo();
        metContractUnit.setText(StringUtils.nullValue(mAgencyInfoVo.getAgencyName()));

        metContractStart.setText(DateUtils.getFormatDateStringWithDateString(vo.getStart_date(), DateUtils.dateFormatYMD));
        metContractEnd.setText(DateUtils.getFormatDateStringWithDateString(vo.getEnd_date(), DateUtils.dateFormatYMD));
        if (StringUtils.getBoolean(vo.getStatus())) {
            radioYes.setChecked(true);
            radioNo.setChecked(false);
        } else {
            radioYes.setChecked(false);
            radioNo.setChecked(true);
        }


    }


    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(KeepContractPropActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_keep_contract_prop;
    }


    @Subscribe
    public void onEventMainThread(KeepUnitEvent event) {
        if (KeepContractUnitListFragment.class.getName().equals(event.getTag())) {
            mAgencyInfoVo = (AgencyInfoVo) event.getData();
            if (mAgencyInfoVo != null) {
                metContractUnit.setText(StringUtils.nullValue(mAgencyInfoVo.getAgencyName()));
            }
        }
    }

    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        /**
         * 维保单位
         */
        if (TextUtils.isEmpty(metContractUnit.getText().toString().trim())) {
            String tipString = getString(R.string.keep_contract_prop_error);
            if (StringUtils.nullValue(sTypeId, "1").equals("2")) {
                tipString = getString(R.string.wuye_unit_prop_error);
            }
            metContractUnit.setError(tipString);
            mHUDUtil.showErrorTip(tipString);
            return false;
        }

        return true;

    }


    @OnClick({R.id.lineContractYear, R.id.metContractYear})
    protected void showYearDialog() {
        if (isEdit && !StringUtils.getBoolean(mKeepContractVo.getStatus())) {
            return;
        }
        showYearMaterialDialog();
    }

    private void showYearMaterialDialog() {
        final List<YearVo> items = getYearDialogData();
        new MaterialDialog.Builder(this).title(R.string.keep_contract_prop_contract_year).adapter(new KeepYearListAdapter(items), new MaterialDialog.ListCallback() {
            @Override
            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                YearVo vo = items.get(which);
                metContractYear.setText(vo.getTitle());
                metContractYear.setTag(vo.getYear() + "");
                dialog.dismiss();
            }
        }).show();
    }

    /**
     * 获取年份列表
     *
     * @return
     */
    private List<YearVo> getYearDialogData() {
        int currentYear = DateUtils.getCurrentYear();
        List<YearVo> result = new ArrayList<>();
        for (int i = currentYear - 5; i < currentYear + 5; i++) {
            YearVo vo = new YearVo(i, DataInfo.getStatusString(i + "年", DataInfo.ColorStatus.STATUS_BLUE));
            result.add(vo);
        }
        return result;

    }


    @OnClick({R.id.lineContractUnit, R.id.metContractUnit})
    protected void showRowUnitPicker() {
        if (isEdit && !StringUtils.getBoolean(mKeepContractVo.getStatus())) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(BundleKey.TYPE_ID, sTypeId);
        if (mAgencyInfoVo != null) {
            bundle.putString(BundleKey.OLD_SELECT_VALUE, StringUtils.nullValue(mAgencyInfoVo.getAgencyCode()));
            UIHelper.showActivity(this, bundle, KeepContractUnitListActivity.class);
        } else {
            UIHelper.showActivity(this, bundle, KeepContractUnitListActivity.class);
        }
    }


    @OnClick({R.id.lineContractStart, R.id.metContractStart})
    protected void showPickStartDate() {
        if (isEdit && !StringUtils.getBoolean(mKeepContractVo.getStatus())) {
            return;
        }
        pickKeepStartDate();
    }

    @OnClick({R.id.lineContractEnd, R.id.metContractEnd})
    protected void showPickEndDate() {
        if (isEdit && !StringUtils.getBoolean(mKeepContractVo.getStatus())) {
            return;
        }
        pickKeepEndDate();
    }


    /**
     * 显示合同开始时间
     */
    private void pickKeepStartDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                String strDate = TimeUtil.transCalendarDate(year, monthOfYear, dayOfMonth);
                //String date = String.format("%s-%s-%s", year, monthOfYear + 1, dayOfMonth);
                if (CommonUtil.strIsEmpty(metContractEnd.getText().toString().trim())) {
                    metContractStart.setText(strDate);
                } else {

                    if (TimeUtil.dateCompareDate(TimeUtil.tranTimeForDate(strDate), TimeUtil.tranTimeForDate(metContractEnd.getText().toString().trim()))) {
                        metContractStart.setText(strDate);
                    } else {
                        mHUDUtil.showErrorTip("开始时间必须小于结束时间");
                    }

                }

            }
        }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
        dpd.setThemeDark(false);
        dpd.vibrate(false);
        dpd.show(getFragmentManager(), "pickKeepStartDate");

    }

    /**
     * 显示合同结束时间
     */
    private void pickKeepEndDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                String strDate = TimeUtil.transCalendarDate(year, monthOfYear, dayOfMonth);
                //String date = String.format("%s-%s-%s", year, monthOfYear + 1, dayOfMonth);
                //metContractEnd.setText(strDate);
                if (CommonUtil.strIsEmpty(metContractStart.getText().toString().trim())) {
                    metContractEnd.setText(strDate);
                } else {

                    if (!TimeUtil.dateCompareDate(TimeUtil.tranTimeForDate(strDate), TimeUtil.tranTimeForDate(metContractStart.getText().toString().trim()))) {
                        metContractEnd.setText(strDate);
                    } else {
                        mHUDUtil.showErrorTip("结束时间必须大于开始时间");
                    }

                }


            }
        }, now.get(Calendar.YEAR) + 1, now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
        dpd.setThemeDark(false);
        dpd.vibrate(false);
        dpd.show(getFragmentManager(), "pickKeepEndDate");
    }

    @OnClick(R.id.btn_submit)
    protected void btnSubmitAction() {
        if (!validateForm()) {
            return;
        }

        mMaterialDialog = getConfirmDialog(getString(R.string.is_submit), new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doPostAction();
                }
            }
        });
        mMaterialDialog.show();

    }


    private void doPostAction() {
        final LemonRequestParams params = new LemonRequestParams("keep_contract", "contract_id", "");
        if (isEdit) {
            params.put("_txtIdValues", mKeepContractVo.getContract_id());
            params.put("contract_id", mKeepContractVo.getContract_id());
        } else {
            params.put("_txtIdValues", "");
            params.put("contract_id", "");
        }
        params.put("txtKeepYear", metContractYear.getTag().toString().trim(), Field.TYPE_STRING);
        params.put("txtStartDate", metContractStart.getText().toString().trim(), Field.TYPE_DATE);
        params.put("txtEndDate", metContractEnd.getText().toString().trim(), Field.TYPE_DATE);
        params.put("chkStatus", radioYes.isChecked() ? "1" : "0", Field.TYPE_INT);
        params.put("txtCompanyCode", StringUtils.nullValue(mCompanyInfo.getCompany_code()), Field.TYPE_STRING);
        params.put("txtKeepCode", StringUtils.nullValue(mAgencyInfoVo.getAgencyCode()), Field.TYPE_STRING);
        params.put("txtTypeId", StringUtils.nullValue(sTypeId), Field.TYPE_INT);

        KeepContactServices.init().saveKeepContractInfoAction(params, isEdit);


    }


    /**
     * 处理所有的网络请求返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_SAFE_KEEP_CONTRACT_SAVE_ACTION == event.getTag()) {//保存表单
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showInfoTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            KeepRefreshEvent refreshEvent = new KeepRefreshEvent();
                            refreshEvent.setTag(KeepRefreshEvent.class.getName());
                            AppService.getBus().post(refreshEvent);
                            callFinish();
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


}
